package org.yu.register.capability;

import net.minecraft.nbt.IntTag;
import net.minecraft.nbt.Tag;
import net.minecraftforge.common.util.INBTSerializable;

@SuppressWarnings("unused")
public class LingQiStorage implements INBTSerializable<Tag> {
    protected int lingQi;
    protected int capacity;
    protected int maxReceive;
    protected int maxExtract;

    public LingQiStorage(int capacity)
    {
        this(capacity, capacity, capacity, 0);
    }

    public LingQiStorage(int capacity, int maxTransfer)
    {
        this(capacity, maxTransfer, maxTransfer, 0);
    }

    public LingQiStorage(int capacity, int maxReceive, int maxExtract)
    {
        this(capacity, maxReceive, maxExtract, 0);
    }

    public LingQiStorage(int capacity, int maxReceive, int maxExtract, int lingQi)
    {
        this.capacity = capacity;
        this.maxReceive = maxReceive;
        this.maxExtract = maxExtract;
        this.lingQi = Math.max(0 , Math.min(capacity, lingQi));
    }


    public int receive(int maxReceive, boolean simulate)
    {
        if (!canReceive())
            return 0;

        int energyReceived = Math.min(capacity - lingQi, Math.min(this.maxReceive, maxReceive));
        if (!simulate)
            lingQi += energyReceived;
        return energyReceived;
    }

    public int extract(int maxExtract, boolean simulate)
    {
        if (!canExtract())
            return 0;

        int energyExtracted = Math.min(lingQi, Math.min(this.maxExtract, maxExtract));
        if (!simulate)
            lingQi -= energyExtracted;
        return energyExtracted;
    }


    public int getStored()
    {
        return lingQi;
    }


    public int getMaxStored()
    {
        return capacity;
    }


    public boolean canExtract()
    {
        return this.maxExtract > 0;
    }


    public boolean canReceive()
    {
        return this.maxReceive > 0;
    }


    public Tag serializeNBT()
    {
        return IntTag.valueOf(this.getStored());
    }

    @Override
    public void deserializeNBT(Tag nbt)
    {
        if (!(nbt instanceof IntTag intNbt))
            throw new IllegalArgumentException("Can not deserialize to an instance that isn't the default implementation");
        this.lingQi = intNbt.getAsInt();
    }
}
